/**
 * T:对比当前网页是否已经存在于Anki当中，如不存在则提供一键添加的功能。
 * S1：获取当前网页标题、URL
 * S2：获取当前Anki WebPage deck中现存的cards
 * S3：对比是否存在当前标题的card
 * S5：如不存在则弹窗询问是否添加
 * S6：一键添加
 */

var pageTitle = "";
var pageUrl = "";
var pageNote = "";
var pageTages = [];
const deckName = "WebPage";
const modelName = "Basic(Title-Url-Note)";
// receiving a message
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  pageTitle = request.pageTitle;
  pageUrl = request.pageUrl;
});
/**

 */
chrome.contextMenus.create({
  title: "WebPage2Anki",
  onclick: async () => {
    let cardsIDList = await getCardsID();
    let cardsInfoList = await getCardsInfo(cardsIDList);
    console.log(cardsInfoList);

    let titleList = cardsInfoList.map((card) => card.fields.Title.value);
    console.log(titleList);
    console.log(pageTitle);
    if (titleList.indexOf(pageTitle) >= 0) {
      alert("已收录，请勿重复添加！");
      return;
    } else {
      await addNotes()
        .then((res) => {
          alert("收录成功！");
        })
        .catch((err) => {
          alert(err);
        });
      await sync();
    }
  },
});
/**
 *
 * @returns 返回卡片详情列表
 */
const sync = () => {
  return new Promise((resolve, reject) => {
    let data = {
      action: "sync",
      version: 6,
    };
    invoke(data.action, data.version, data.params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
/**
 *
 * @returns 返回卡片详情列表
 */
const addNotes = () => {
  return new Promise((resolve, reject) => {
    let data = {
      action: "addNote",
      version: 6,
      params: {
        note: {
          deckName: deckName,
          modelName: modelName,
          fields: {
            Title: pageTitle,
            Url: pageUrl,
            Note: pageNote,
          },
          tags: pageTages,
        },
      },
    };
    invoke(data.action, data.version, data.params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
/**
 *
 * @returns 返回卡片详情列表
 */
const getCardsInfo = (cardsIDList) => {
  return new Promise((resolve, reject) => {
    let data = {
      action: "cardsInfo",
      version: 6,
      params: {
        cards: cardsIDList,
      },
    };
    invoke(data.action, data.version, data.params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 *
 * @returns 返回卡片ID列表
 */
const getCardsID = () => {
  return new Promise((resolve, reject) => {
    let data = {
      action: "findCards",
      version: 6,
      params: {
        query: "deck:" + deckName,
      },
    };
    invoke(data.action, data.version, data.params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
/**
 *
 * @param {String} action
 * @param {Number} version
 * @param {Object} params
 * @example await invoke("createDeck", 6, { deck: "test1" });
            const result = await invoke("deckNames", 6);
            console.log(`got list of decks: ${result}`);
 * @returns
 */
function invoke(action, version = 6, params = {}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.addEventListener("error", () => reject("failed to issue request"));
    xhr.addEventListener("load", () => {
      try {
        const response = JSON.parse(xhr.responseText);
        if (Object.getOwnPropertyNames(response).length != 2) {
          throw "response has an unexpected number of fields";
        }
        if (!response.hasOwnProperty("error")) {
          throw "response is missing required error field";
        }
        if (!response.hasOwnProperty("result")) {
          throw "response is missing required result field";
        }
        if (response.error) {
          throw response.error;
        }
        resolve(response.result);
      } catch (e) {
        reject(e);
      }
    });

    xhr.open("POST", "http://127.0.0.1:8765");
    xhr.send(JSON.stringify({ action, version, params }));
  });
}
